package rdatabase

import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
	"strings"
)

type InitMongodb struct {
	User     string `json:"user"`
	Password string `json:"Password"`
	Host     string `json:"host"`
	Port     uint   `json:"port"` //27017
	Database string `json:"database"`
}

func (p *InitMongodb) Connect() *mongo.Database {
	_dsn := fmt.Sprintf(
		"mongodb://%v:%v/?retryWrites=true&w=majority",
		p.Host, p.Port)
	if p.User != "" && p.Password != "" {
		_dsn = fmt.Sprintf(
			"mongodb://%v:%v@%v:%v/?retryWrites=true&w=majority",
			p.User, strings.ReplaceAll(p.Password, "@", "%40"), p.Host, p.Port)
	}
	_ops := options.ServerAPI(options.ServerAPIVersion1).SetStrict(true).SetDeprecationErrors(true)
	_client, err := mongo.Connect(context.Background(), options.Client().ApplyURI(_dsn).SetServerAPIOptions(_ops))
	if err != nil {
		log.Fatal("连接 Mongodb 数据库", p.Database, "失败：", err)
	}
	err = _client.Ping(context.Background(), nil)
	if err != nil {
		log.Fatal("连接 Mongodb 数据库", p.Database, "Ping失败：", err)
	}
	database := _client.Database(p.Database)
	log.Println("连接 Mongodb 数据库", p.Database, "完成")
	return database
}
